package com.example.springboot.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Publisher;
import com.example.springboot.service.PublisherService;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

@CrossOrigin
@RestController

@RequestMapping("/publisher")
public class PublisherController {
    @Autowired
    PublisherService publisherService;
    
    @PostMapping("/add")
    public Result add(@RequestBody Publisher publisher){
        try{
            publisherService.save(publisher);
        }catch(Exception e){
            return Result.error("插入数据错误");
        }
        return Result.success();
    }
    
    @PutMapping("/update")
    public Result update(@RequestBody Publisher publisher){
        try{
            publisherService.updateById(publisher);
        }catch(Exception e){
            return Result.error("更新数据错误");
        }
        return Result.success();
    }
    
    @DeleteMapping("/delete/{name}")
    public Result delete(@PathVariable String name){
        try{
            publisherService.removeById(name);
        }catch(Exception e){
            return Result.error("删除数据错误");
        }
        return Result.success();
    }

        @DeleteMapping("/delete/batch")
        public Result batchDelete(@RequestBody List<String> names) {
        publisherService.removeBatchByIds(names);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Publisher> publisherList=publisherService.list();
        return Result.success(publisherList);
    }

    @GetMapping("/selectByName/{name}")
    public Result selectByName(@PathVariable String name){
        Publisher publisher=publisherService.getById(name);
        return Result.success(publisher);
    }
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String name) {
        QueryWrapper<Publisher> queryWrapper = new QueryWrapper<Publisher>();
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        // select * from publisher where name like '%#{name}%'
        Page<Publisher> page = publisherService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String name,
                           @RequestParam(required = false) String names,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<Publisher> list;
        QueryWrapper<Publisher> queryWrapper = new QueryWrapper<Publisher>();
        if(StrUtil.isNotBlank(names)){
            List<String> namesArr=Arrays.stream(names.split(",")).collect(Collectors.toList());
            queryWrapper.in("name",namesArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);

        }
        list=publisherService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("供货商信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Publisher> publisherList = reader.readAll(Publisher.class);
        // 写入数据到数据库
        try {
            publisherService.saveBatch(publisherList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }
}
